﻿using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PartsRetrospect.Comm
{
    /// <summary>
    /// SFTP操作类
    /// </summary>
    public class SecureFileTransfer
    {
        private string _hostname;
        private int _hostport;
        private string _username;
        private string _password;
        /// <summary>
        /// 连接异常
        /// </summary>
        public event Action OnConnectionException;
        /// <summary>
        /// 单例模式
        /// </summary>
        private static SecureFileTransfer instance = new SecureFileTransfer();
        public static SecureFileTransfer getInstance(string host, int hostport, string user, string pass)
        {
            if (!host.Equals(instance._hostname))
            {
                instance = new SecureFileTransfer(host, hostport, user, pass);
            }

            return instance;
        }
        public SecureFileTransfer(string host, int hostport, string user, string pass)
        {
            this._hostname = host;
            this._hostport = hostport;
            this._username = user;
            this._password = pass;
        }
        public SecureFileTransfer()
        {

        }



        public Boolean putFile(string frompath, string remotePath)
        {
            try
            {
                using (var sftpClient = new SftpClient(this._hostname, this._hostport, this._username, this._password))
                {
                    sftpClient.Connect();
                    Stream ss = File.Open(frompath, FileMode.Open);
                    string[] strings = frompath.Split('\\');
                    var newRemote = remotePath + "/" + strings[strings.Length - 1];
                    sftpClient.UploadFile(ss, newRemote);
                    sftpClient.Dispose();
                    return true;
                }
            }
            catch (Exception e)
            {
                OnConnectionException?.BeginInvoke(null, null);
                throw new Exception("上传出现错误" + DateTime.Now + "错误原因:" + e.Message + "-------" + e.StackTrace);
            }
        }

        public Boolean ConnectCheck()
        {
            try
            {
                using (var sftpClient = new SftpClient(this._hostname, this._hostport, this._username, this._password))
                {
                    sftpClient.Connect();
                    sftpClient.Dispose();
                    return true;
                }
            }
            catch (Exception e)
            {
                OnConnectionException?.BeginInvoke(null, null);
                throw new Exception("连接错误" + DateTime.Now + "错误原因:" + e.Message + "-------" + e.StackTrace);
            }
        }
    }
}
